const express = require("express");
const router = express.Router();
const pool = require("../pool.js");
const utils = require("../utils/index.js");
const { systemSettings } = require("../utils/menuString.js");

var moment = require('moment');
const multer = require('multer');
const path = require('path');
const fs = require('fs'); 

// 配置上传文件存储位置和文件名
// const storage = multer.diskStorage({
//     destination: function (req, file, cb) {
//         cb(null, './uploads/')  // 上传的文件存储在 uploads 目录中
//     },
//     filename: function (req, file, cb) {
//         // 使用当前时间戳和随机数作为上传后的文件名
//         const uniqueSuffix = Date.now() + '_' + Math.round(Math.random() * 1E9);
//         cb(null, uniqueSuffix + path.extname(file.originalname))
//     }
// });

// 配置上传文件存储位置和文件名
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        const uploadDir = './uploads/';
        // 检查目录是否存在，不存在则创建
        if (!fs.existsSync(uploadDir)) {
            fs.mkdirSync(uploadDir, { recursive: true });
        }
        cb(null, uploadDir);  // 上传的文件存储在 uploads 目录中
    },
    filename: function (req, file, cb) {
        // 使用当前时间戳和随机数作为上传后的文件名
        const uniqueSuffix = Date.now() + '_' + Math.round(Math.random() * 1E9);
        cb(null, uniqueSuffix + path.extname(file.originalname))
    }
});

// 创建 multer 实例
// const upload = multer({
//     storage: storage,
//     limits: {
//         fileSize: 20 * 1024 * 1024, // 限制单个文件大小为 2MB
//         files: 10, // 最多允许上传 10 个文件
//     },
//     fileFilter: (req, file, cb) => {
//         const allowedTypes = ['image/jpeg', 'image/png'];
//         if (allowedTypes.includes(file.mimetype)) {
//             cb(null, true);
//         } else {
//             cb(new Error('Unsupported file type. Only JPEG and PNG are allowed.'));
//         }
//     },
// }); //50m limits: { fileSize: 50 * 1024 * 1024 } }); //50m


const upload = multer({
    storage: storage,
    limits: {
        fileSize: 20 * 1024 * 1024, // 20MB 限制
        files: 10,
    },
    fileFilter: (req, file, cb) => {
        // 增加更严格的文件类型检查
        const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
        
        // 检查 MIME 类型
        if (!allowedTypes.includes(file.mimetype)) {
            return cb(new Error('不支持的文件类型'));
        }

        // 检查文件扩展名
        const ext = path.extname(file.originalname).toLowerCase();
        if (!allowedExtensions.includes(ext)) {
            return cb(new Error('不支持的文件扩展名'));
        }

        cb(null, true);
    }
});



// 配置上传文件存储位置和文件名
const storage1 = multer.diskStorage({
    destination: function (req, file, cb) {
        const uploadDir = './uploads/zsfile/';
        // 检查目录是否存在，不存在则创建
        if (!fs.existsSync(uploadDir)) {
            fs.mkdirSync(uploadDir, { recursive: true });
        }
        cb(null, uploadDir);  // 上传的文件存储在 uploads 目录中
    },
    filename: function (req, file, cb) {
        // 使用当前时间戳和随机数作为上传后的文件名
        const uniqueSuffix = Date.now() + '_' + Math.round(Math.random() * 1E9);
        cb(null, uniqueSuffix + path.extname(file.originalname))
    }
});



const upload1 = multer({
    storage: storage1,
    limits: {
        fileSize: 20 * 1024 * 1024, // 20MB 限制
        files: 10,
    },
    fileFilter: (req, file, cb) => {
        // 增加更严格的文件类型检查
        const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
        const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.pdf'];
        
        // 检查 MIME 类型
        if (!allowedTypes.includes(file.mimetype)) {
            return cb(new Error('不支持的文件类型'));
        }

        // 检查文件扩展名
        const ext = path.extname(file.originalname).toLowerCase();
        if (!allowedExtensions.includes(ext)) {
            return cb(new Error('不支持的文件扩展名'));
        }

        cb(null, true);
    }
});


function getCurrentTimeString() {
  const now = new Date();

  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要+1
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

console.log(getCurrentTimeString());
// 输出: 2023-10-27 15:30:45


//登录
router.post("/login", async (req, res) => {
    let sql = "SELECT id,admin,more_id FROM user WHERE username=? AND password=?", obj = req.body;
    console.log(obj.name, obj)
    pool.query(sql, [obj.name, obj.pwd], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        if (result.length == 0) return res.send(utils.returnData0({ code: -1, msg: "请输入正确的用户名和密码！", err, req }));
        let uid = result[0].id, admin = result[0].admin, name = obj.name;
        let token = utils.setToken({ uid });
        res.send(utils.returnData0({ data: { uid, name, token, admin } }));
    });
});

//获取用户信息
router.post("/getUserInfo", async (req, res) => {
    let user = await utils.getUserRole(req, res);
    let sql = `SELECT b.menu_bg AS menuBg,b.menu_sub_bg AS menuSubBg,b.menu_text AS menuText,b.menu_active_text AS menuActiveText,b.menu_sub_active_text AS menuSubActiveText,b.menu_hover_bg AS menuHoverBg FROM theme AS b WHERE user_id=?`;
    pool.query(sql, [user.user.id], (err, result) => {
        if (err || result.length === 0) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: { ...user, theme: result[0] } }));
    })

})

//添加报警
router.post("/addAlarm", async (req, res) => {
    let sql = "INSERT INTO alarm(name, number,desc_en,desc_ch,create_time) VALUES (?,?,?,?,?)";
    obj = req.body;
    console.log(obj);
    pool.query(sql, [obj.name, obj.number, obj.desc_en, obj.desc_ch, getCurrentTimeString()], async (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err }));
        insertId = result.insertId;
        res.send(utils.returnData0({ data: { insertId } }));
    });
});


//查询报警
router.post("/getAlarmList", async (req, res) => {

    let obj = req.body;
    let {page,size}=utils.pageSize(obj.page, obj.size);

    // // 构建查询条件
    // let where = '';
    // const params = [];
    
    // if (name) {
    //   where = 'WHERE name LIKE ?';
    //   params.push(`%${name}%`);
    // }

    let { total } = await utils.getSum({ name: "alarm", where: `WHERE name LIKE "%${obj.name || ''}%"`, res, req });
    // console.log(total);
    // let sql = `select * from xm`;

    let sql = `SELECT * from alarm WHERE name LIKE "%${obj.name || ''}%" LIMIT ?,?`;
    pool.query(sql, [page,size], async (err, result) => {
        // console.log(result);
        if (err) return res.send(utils.returnData({ code: -1, err, req }));

        res.send(utils.returnData0({ data: result, total: total }));
    });
});

//修改报警信息
router.post("/upAlarm", async (req, res) => {


    obj = req.body;

    let sql = "update alarm set name=?, number=?, desc_en=?, desc_ch=? where id=?";

    pool.query(sql, [obj.name, obj.number, obj.desc_en, obj.desc_ch, obj.id], (err, result) => {

        res.send(utils.returnData0({}));
    });
});

//删除报警信息
router.post("/delAlarm", async (req, res) => {

    obj = req.body;

    let sql = "delete from alarm where id=?";

    pool.query(sql, [obj.id], (err, result) => {

        res.send(utils.returnData0({}));
    });
});

//添加故障
router.post("/addFault", async (req, res) => {
    let sql = "INSERT INTO fault(name, cause, position, grade, info, create_time) VALUES (?,?,?,?,?,?)";
    obj = req.body;
    console.log(obj);
    pool.query(sql, [obj.name, obj.cause, obj.position, obj.grade, obj.info, getCurrentTimeString()], async (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err }));
        insertId = result.insertId;
        res.send(utils.returnData0({ data: { insertId } }));
    });
});



//查询故障
router.post("/getFaultList", async (req, res) => {

    let obj = req.body;
    let {page,size}=utils.pageSize(obj.page,obj.size);
    let { total } = await utils.getSum({ name: "fault", where:  `WHERE name LIKE "%${obj.name || ''}%"`, res, req });
    // console.log(total);
    // let sql = `select * from xm`;
    let sql = `SELECT * from fault WHERE name LIKE "%${obj.name || ''}%" LIMIT ?,?`;
    pool.query(sql, [page,size],async (err, result) => {
        // console.log(result);
        if (err) return res.send(utils.returnData({ code: -1, err, req }));

        res.send(utils.returnData0({ data: result, total: total }));
    });
});

//修改故障信息
router.post("/upFault", async (req, res) => {

    obj = req.body;
    let sql = "update fault set name=?, cause=?, position=?, grade=?, info=? where id=?";
    pool.query(sql, [obj.name, obj.cause, obj.position, obj.grade, obj.info, obj.id], (err, result) => {
        res.send(utils.returnData0({}));
    });
});

//删除故障信息
router.post("/delFault", async (req, res) => {

    obj = req.body;

    let sql = "delete from fault where id=?";

    pool.query(sql, [obj.id], (err, result) => {

        res.send(utils.returnData0({}));
    });
});


//查询设备
router.post("/getPartList", async (req, res) => {

    let obj = req.body;
    let {page,size}=utils.pageSize(obj.page,obj.size);

    // // 构建查询条件
    // let where = '';
    // const params = [];
    
    // if (name) {
    //   where = 'WHERE name LIKE ?';
    //   params.push(`%${name}%`);
    // }

    let { total } = await utils.getSum({ name: "parts", where:  `WHERE name LIKE "%${obj.name || ''}%"`, res, req });
    // console.log(total);
    // let sql = `select * from xm`;

    let sql = `SELECT * from parts WHERE name LIKE "%${obj.name || ''}%" LIMIT ?,?`;
    pool.query(sql, [page,size],async (err, result) => {
        // console.log(result);
        if (err) return res.send(utils.returnData({ code: -1, err, req }));

        res.send(utils.returnData0({ data: result, total: total }));
    });
});

//修改设备信息
router.post("/upPart", async (req, res) => {


    obj = req.body;

    let sql = "update parts set partNum=?, sszt=?, name=?, ggxh=?, cgdj=?, cfwz=? where id=?";

    pool.query(sql, [obj.partNum, obj.sszt, obj.name, obj.ggxh, obj.cgdj, obj.cfwz, obj.id], (err, result) => {

        res.send(utils.returnData0({}));
    });
});

//删除设备信息
router.post("/delPart", async (req, res) => {

    obj = req.body;

    let sql = "delete from parts where id=?";

    pool.query(sql, [obj.id], (err, result) => {

        res.send(utils.returnData0({}));
    });
});

//添加设备
router.post("/addPart", async (req, res) => {
    let sql = "INSERT INTO parts(partNum, sszt, name, ggxh, cgdj, cfwz, create_time) VALUES (?,?,?,?,?,?,?)";
    obj = req.body;
    console.log(obj);
    pool.query(sql, [obj.partNum, obj.sszt, obj.name, obj.ggxh, obj.cgdj, obj.cfwz, getCurrentTimeString()], async (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err }));
        insertId = result.insertId;
        res.send(utils.returnData0({ data: { insertId } }));
    });
});


//查询知识
router.post("/getZsglList", async (req, res) => {

    let obj = req.body;
    let {page,size}=utils.pageSize(obj.page,obj.size);

    let { total } = await utils.getSum({ name: "zsgl", where:  `WHERE name LIKE "%${obj.name || ''}%"`, res, req });
    // console.log(total);
    // let sql = `select * from xm`;

    let sql = `SELECT * from zsgl WHERE name LIKE "%${obj.name || ''}%" LIMIT ?,?`;
    pool.query(sql, [page,size],async (err, result) => {
        // console.log(result);
        if (err) return res.send(utils.returnData({ code: -1, err, req }));

        res.send(utils.returnData0({ data: result, total: total }));
    });
});


//删除知识信息
router.post("/delZsgl", async (req, res) => {

    obj = req.body;

    let sql = "delete from zsgl where id=?";

    pool.query(sql, [obj.id], (err, result) => {

        res.send(utils.returnData0({}));
    });
});

//添加知识
router.post("/addZsgl", async (req, res) => {
    let sql = "INSERT INTO zsgl(name, remark, url, create_time) VALUES (?,?,?,?)";
    obj = req.body;
    console.log(obj);
    pool.query(sql, [obj.name, obj.remark, obj.url, getCurrentTimeString()], async (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err }));
        insertId = result.insertId;
        res.send(utils.returnData0({ data: { insertId } }));
    });
});

//修改设备信息
router.post("/upZsgl", async (req, res) => {


    obj = req.body;

    let sql = "update zsgl set name=?, remark=? where id=?";

    pool.query(sql, [obj.name, obj.remark, obj.id], (err, result) => {

        res.send(utils.returnData0({}));
    });
});

//添加决策树
router.post("/addJcs", async (req, res) => {
    // res.send(utils.returnData0({ data: { insertId: 1 } }));

    let sql = "INSERT INTO jcs(parent_id, jcs_name, jcs_info, name, detail, is_leaf, create_time) VALUES (?,?,?,?,?,?,?)";
    obj = req.body;
    console.log(obj);
    // res.send(utils.returnData0({ data: {} }));
    // return;
    // await utils.existName({sql: "SELECT id FROM user WHERE  name=?", name: obj.name,res,msg:"用户名已被使用！",req});
    pool.query(sql, [-1, obj.jcs_name, obj.jcs_info, obj.name, obj.detail, obj.is_leaf, getCurrentTimeString()], async (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err }));
        insertId = result.insertId;
        for (let i = 0; i < obj.alarmIds.length; i++) {
            let alarmSql = "INSERT INTO jcs_alarm(jcs_id, alarm_id, create_time) VALUES (" + insertId.toString() + ", " + obj.alarmIds[i] + ", '" + getCurrentTimeString() + "')";
            console.log(alarmSql);
            let alarm = await utils.findBySql(alarmSql);
        }
        for (let i = 0; i < obj.faultIds.length; i++) {
            let faultSql = "INSERT INTO jcs_fault(jcs_id, fault_id, create_time) VALUES (" + insertId.toString() + ", " + obj.faultIds[i] + ", '" + getCurrentTimeString() + "')";
            console.log(faultSql);
            let fault = await utils.findBySql(faultSql);
        }
        res.send(utils.returnData0({ data: { insertId } }));
    });
});


// 插入子节点
router.post("/insertJcsNode", async (req, res) => {
    // res.send(utils.returnData0({ data: { insertId: 1 } }));

    let sql = "INSERT INTO jcs(parent_id, name, detail, is_leaf, node_text,create_time) VALUES (?,?,?,?,?,?)";
    obj = req.body;
    // console.log(obj);
    // res.send(utils.returnData0({ data: {} }));
    // return;
    // await utils.existName({sql: "SELECT id FROM user WHERE  name=?", name: obj.name,res,msg:"用户名已被使用！",req});
    pool.query(sql, [obj.parent_id, obj.name, obj.detail, obj.is_leaf, obj.node_text, getCurrentTimeString()], async (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err }));
        insertId = result.insertId;

        res.send(utils.returnData0({ data: { insertId } }));
    });
});


//查询决策树列表
router.post("/getJcsList", async (req, res) => {
    let obj = req.body;
    let {page,size}=utils.pageSize(obj.page,obj.size);
    let { total } = await utils.getSum({ name: "jcs", where:  `WHERE jcs_name LIKE "%${obj.name || ''}%"`, res, req });
    // console.log(total);
    // let sql = `select * from xm`;
    let sql = `SELECT id, jcs_name, jcs_info, create_time from jcs where parent_id=-1 and jcs_name LIKE "%${obj.name || ''}%" LIMIT ?,?`;
    pool.query(sql, [page,size],async (err, result) => {
        if (err) return res.send(utils.returnData({ code: -1, err, req }));

        res.send(utils.returnData0({ data: result, total: total }));
    });
});


// //查询决策树
// router.post("/getJcs", async (req, res) => {

//     let obj = req.body;
//     // let {page,size}=utils.pageSize(obj.page,obj.size);
//     // let { total } = await utils.getSum({ name: "fault", where: ``, res, req });
//     // console.log(obj);
//     // let sql = `select * from xm`;

//     let treeData = {}
//     let sql = "SELECT * from jcs where id=?";
//     // x先查出根节点
//     pool.query(sql, [obj.id], async (err, result) => {
//         // console.log(result);
//         if (err) return res.send(utils.returnData({ code: -1, err, req }));
//         treeids = []
//         if (result.length > 0) {
//             treeData = result[0];
//             treeids.push({ "id": result[0].id, "node": result });
//             while (treeids.length > 0) {
//                 let childsql = "SELECT * from jcs where parent_id=" + treeids[0].id;
//                 console.log('child sql:', childsql);
//                 let childlist = await utils.findBySql(childsql);
//                 treeids[0]["node"].children = [];
//                 // 遍历孩子节点
//                 console.log('childlist', childlist);
//                 for (let i = 0; i < childlist.length; i++) {
//                     treeids[0]["node"].children.push(childlist[i]);
//                     console.log('treeids[0]["node"]', treeData);
//                     treeids.push({ "id": childlist[i].id, "node": childlist[i] });
//                 }
//                 // 移除第一个元素
//                 treeids.shift();
//             }
//         }

//         console.log('treeData', treeData);

//         res.send(utils.returnData0({ data: treeData }));

//     });
// });


router.post("/getJcs", async (req, res) => {
    let obj = req.body;
    let treeData = {};

    let sql = "SELECT * from jcs where id=?";
    pool.query(sql, [obj.id], async (err, result) => {
        if (err) return res.send(utils.returnData({ code: -1, err, req }));

        if (result.length > 0) {
            treeData = result[0];
            treeData.children = []; // 初始化根节点的 children

            let treeids = [{ id: treeData.id, node: treeData }];

            // BFS遍历树
            while (treeids.length > 0) {
                // 取出当前节点
                let currentNode = treeids.shift();

                // 查询当前节点的图片列表
                let imgsql = "SELECT * from images where is_del=0 and jcs_id=" + currentNode.id;
                let imgs = await utils.findBySql(imgsql);
                currentNode.images = imgs;

                // 查找子节点
                let childsql = "SELECT * from jcs where parent_id=" + currentNode.id;
                console.log('child sql:', childsql);
                let childlist = await utils.findBySql(childsql);

                // 如果有子节点，初始化 children 数组
                currentNode.node.children = currentNode.node.children || [];

                // 遍历子节点并构建树
                for (let i = 0; i < childlist.length; i++) {
                    const childNode = childlist[i];
                    childNode.children = []; // 初始化子节点的 children

                    // 将子节点添加到当前节点的 children
                    currentNode.node.children.push(childNode);

                    // 将子节点加入队列
                    treeids.push({ id: childNode.id, node: childNode });
                }
            }
        }

        // console.log('treeData', JSON.stringify(treeData, null, 2));

        res.send(utils.returnData0({ data: treeData }));
    });
});



//查询决策树节点
router.post("/getJcsNode", async (req, res) => {

    let obj = req.body;

    let node = await getJcsNode(obj.id);
    console.log('node', node);
    res.send(utils.returnData0({ data: node }));

});

//编辑决策树节点
router.post("/upJcsNode", async (req, res) => {

    obj = req.body;
    let sql = `update jcs set name='${obj["name"]}', node_text='${obj["node_text"]}', is_leaf='${obj["is_leaf"]}', detail='${obj["detail"]}' where id=${obj["id"]}`;

    console.log(sql);
    let result = await utils.findBySql(sql);

    // // 修改图片
    // let picsql = "SELECT * from images where jcs_id=" + result[0].id + " and is_del=0";
    // // console.log(picsql);
    // let piclist = await utils.findBySql(picsql);

    res.send(utils.returnData0({ msg: "已更新节点信息" }));

});

// 通过id查询该节点信息
async function getJcsNode(id) {

    let sql = "SELECT * from jcs where id=" + id;

    let result = await utils.findBySql(sql);
    if (result && result.length > 0) {
        // 查询图片列表
        let picsql = "SELECT * from images where jcs_id=" + result[0].id + " and is_del=0";
        // console.log(picsql);
        let piclist = await utils.findBySql(picsql);
        result[0].images = piclist;

    }
    return result[0];
}


// 通过id查询该根节点信息
async function getJcsRootNode(id) {

    let sql = "SELECT * from jcs where id=" + id;

    let result = await utils.findBySql(sql);
    if (result && result.length > 0) {
        // 查询图片列表
        let picsql = "SELECT * from images where jcs_id=" + result[0].id + " and is_del=0";
        // console.log(picsql);
        let piclist = await utils.findBySql(picsql);
        result[0].images = piclist;

        // 查询警告列表
        let alarmsql = "SELECT alarm.id, alarm.`name` FROM jcs_alarm INNER JOIN alarm ON jcs_alarm.alarm_id = alarm.id and jcs_alarm.jcs_id=" + result[0].id;
        // console.log(alarmsql);
        let alarmlist = await utils.findBySql(alarmsql);
        result[0].alarmIds = alarmlist;

        // 查询故障列表
        let faultsql = "SELECT fault.id, fault.`name` FROM jcs_fault INNER JOIN fault ON jcs_fault.fault_id = fault.id and jcs_fault.jcs_id=" + result[0].id;
        // console.log(faultsql);
        let faultlist = await utils.findBySql(faultsql);
        result[0].faultIds = faultlist;
    }
    console.log(result[0]);
    return result[0];
}


//修改决策树
router.post("/upJcs", async (req, res) => {

    obj = req.body;
    let sql = "update fault set name=?, cause=?, position=?, grade=?, info=? where id=?";
    pool.query(sql, [obj.name, obj.cause, obj.position, obj.grade, obj.info, obj.id], (err, result) => {
        res.send(utils.returnData0({}));
    });
});

//删除决策树
router.post("/delJcs", async (req, res) => {

    obj = req.body;

    //  删除列表
    let treeids = [{ id: obj.id }];

    while (treeids.length > 0) {
        // 取出当前节点
        let currentNode = treeids.shift();

        // 查找子节点
        let childsql = "SELECT * from jcs where parent_id=" + currentNode.id;


        let childlist = await utils.findBySql(childsql);

        // 遍历子节点并逐步删除
        for (let i = 0; i < childlist.length; i++) {
            const childNode = childlist[i];
            childNode.children = []; // 初始化子节点的 childre

            // 将子节点加入队列
            treeids.push({ id: childNode.id });
        }


        let delsql = "delete from jcs where id=" + currentNode.id;

        // 删除当前节点
        let delres = await utils.findBySql(delsql);

        delsql = "update images set is_del=1 where jcs_id=" + currentNode.id;

        // 软删除当前的图片
        delres = await utils.findBySql(delsql);
    }

    res.send(utils.returnData0({ code: 1, msg: "删除成功" }));
});


//删除图片
router.post("/delPic", async (req, res) => {

    obj = req.body;

    delsql = "update images set is_del=1 where id=" + obj.id;

    // 软删除当前的图片
    delres = await utils.findBySql(delsql);

    res.send(utils.returnData0({ code: 1, msg: "删除成功" }));
});


// //上传照片
// router.post("/upload",
//     upload.array('images', 10), //最多上传10个文件
//     async (req, res) => {
//         console.log('上传的文件信息:', req.files);
//         let imgs_url = "";
//         console.log('body:', req.body);
//         obj = req.body;
//         if (req.files) {
//             for (i = 0; i < req.files.length; i++) {
//                 let addpicSql = "INSERT INTO images(jcs_id, url, create_time) VALUES (" + obj.jcs_id.toString() + ", " + "'/uploads/" + req.files[i].filename + "', '" + (new Date()).toISOString() + "')";
//                 console.log(addpicSql);
//                 let fault = await utils.findBySql(addpicSql);
//                 if (fault.affectedRows > 0) {
//                     ;
//                 } else {
//                     console.log("上传图片失败", addpicSql);
//                 }
//             }
//             res.send(utils.returnData0({ code: 1, msg: "上传图片成功" }));
//         }
//     });

// 上传照片
// router.post("/upload", upload.array('images', 10), async (req, res) => {
//     console.log('上传的文件信息:', req.files);
//     console.log('body:', req.body);

//     const { jcs_id } = req.body; // 从请求体中获取 jcs_id

//     if (!req.files || req.files.length === 0) {
//         return res.status(400).json({ code: 0, msg: "未上传文件" });
//     }

//     try {
//         for (let i = 0; i < req.files.length; i++) {
//             const file = req.files[i];
//             const url = `/uploads/${file.filename}`;
//             // const create_time = new Date().toISOString();
//             const create_time = moment().format('YYYY-MM-DD HH:mm:ss');

//             // 使用参数化查询避免 SQL 注入
//             const addpicSql = `
//                 INSERT INTO images(jcs_id, url, create_time)
//                 VALUES (?, ?, ?)
//             `;
//             const params = [jcs_id, url, create_time];

//             console.log('执行 SQL:', addpicSql, '参数:', params);

//             // 执行 SQL
//             const result = await utils.findBySql(addpicSql, params);

//             // 检查是否插入成功
//             if (!result || result.affectedRows === 0) {
//                 console.error("上传图片失败:", addpicSql);
//                 return res.status(500).json({ code: 0, msg: "上传图片失败" });
//             }
//         }

//         // 所有文件上传成功
//         res.json({ code: 1, msg: "上传图片成功" });
//     } catch (error) {
//         console.error("上传图片时发生错误:", error);
//         res.status(500).json({ code: 0, msg: "服务器内部错误" });
//     }
// });

// 改进错误处理
router.post("/upload", upload.array('images', 10), async (req, res) => {
    res.set({
        'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        'Pragma': 'no-cache',
        'Expires': '-1'
    });
    try {
        // 验证请求
        if (!req.files || req.files.length === 0) {
            return res.status(400).json({ 
                code: 0, 
                msg: "未上传文件" 
            });
        }

        const { jcs_id } = req.body;
        if (!jcs_id) {
            return res.status(400).json({
                code: 0,
                msg: "缺少必要参数 jcs_id"
            });
        }

        // 处理上传
        const results = await Promise.all(req.files.map(async file => {
            const url = `/uploads/${file.filename}`;
            const create_time = moment().format('YYYY-MM-DD HH:mm:ss');

            const addpicSql = `
                INSERT INTO images(jcs_id, url, create_time)
                VALUES (?, ?, ?)
            `;
            return await utils.findBySql(addpicSql, [jcs_id, url, create_time]);
        }));

        // 检查所有插入是否成功
        if (results.some(r => !r || r.affectedRows === 0)) {
            throw new Error("部分图片上传失败");
        }

        res.json({ code: 1, msg: "上传图片成功" });

    } catch (error) {
        // 删除已上传的文件
        if (req.files) {
            req.files.forEach(file => {
                const filePath = path.join('./uploads', file.filename);
                fs.unlink(filePath, err => {
                    if (err) console.error('清理失败的上传文件时出错:', err);
                });
            });
        }

        console.error("上传处理错误:", error);
        res.status(500).json({ 
            code: 0, 
            msg: "服务器内部错误",
            error: error.message 
        });
    }
});



// 上传文件
router.post("/uploadFile", upload1.array('images', 1), async (req, res) => {
    res.set({
        'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        'Pragma': 'no-cache',
        'Expires': '-1'
    });
    try {
        // 验证请求
        if (!req.files || req.files.length === 0) {
            return res.status(400).json({ 
                code: 0, 
                msg: "未上传文件" 
            });
        }

        const { id } = req.body;
        if (!id) {
            return res.status(400).json({
                code: 0,
                msg: "缺少必要参数 id"
            });
        }

        console.log('上传的文件信息:', req.files);
        console.log('body:', req.body);

        // 处理上传
        const results = await Promise.all(req.files.map(async file => {
            const url = `/uploads/zsfile/${file.filename}`;
            const create_time = moment().format('YYYY-MM-DD HH:mm:ss');

            const addZsglSql = `
                update zsgl set url=? where id=?
            `;
            return await utils.findBySql(addZsglSql, [url, id, ]);
        }));

        // 检查所有插入是否成功
        if (results.some(r => !r || r.affectedRows === 0)) {
            throw new Error("部分图片上传失败");
        }

        res.json({ code: 1, msg: "上传图片成功" });

    } catch (error) {
        // 删除已上传的文件
        if (req.files) {
            req.files.forEach(file => {
                const filePath = path.join('./uploads/zsfile', file.filename);
                fs.unlink(filePath, err => {
                    if (err) console.error('清理失败的上传文件时出错:', err);
                });
            });
        }

        console.error("上传处理错误:", error);
        res.status(500).json({ 
            code: 0, 
            msg: "服务器内部错误",
            error: error.message 
        });
    }
});



function getRouter(req, res, sidebar = false) {
    return new Promise(async (resolve, reject) => {
        let sql = "SELECT id,parent_id AS parentId,path,hidden,redirect,always_show AS alwaysShow,name,layout,parent_view AS parentView,meta,component,sort,update_time AS updateTime,alone,role_key AS roleKey,menu_type AS menuType FROM router_menu ORDER BY sort ASC, update_time DESC";
        let userRole = await utils.getUserRole(req, res);
        if (userRole == -1) return res.send(utils.returnData0({ code: -1, req }));
        if (!userRole.userRole || userRole.userRole == null || userRole.userRole == "null") userRole.userRole = "";
        //角色权限
        let roles = userRole.userRole.split(",");
        pool.query(sql, (err, result) => {
            if (err) return res.send(utils.returnData0({ code: -1, err, req }));
            let list = [...result], routerArr = [];
            let filterAsyncRoutes = (lists, parentId, pathView = "") => {
                let resArr = [], obj = {};
                lists.map((t) => {
                    let objs = { ...t };
                    try { objs.meta = JSON.parse(objs.meta); } catch (err) { objs.meta = {}; }
                    objs.title = objs.meta.title || "---";
                    objs.pathView = t.path;
                    //按钮自动隐藏
                    if (objs.menuType === "F") objs.hidden = 1;
                    //递归
                    if (objs.parentId == parentId) {
                        objs.path = pathView + objs.path;
                        obj = { ...objs, children: filterAsyncRoutes(list, objs.id, objs.path) };
                        //菜单下有子级，单独拿出来
                        if (obj.menuType === "C" && obj.children && obj.children.length != 0) {
                            routerArr.push(...obj.children)
                            sidebar && delete obj.children;
                        }
                        //如果是总管理
                        if (userRole.user.admin == 1 || userRole.roleAdmin) { resArr.push(obj); } else {
                            //只拿角色权限通过的
                            if (roles.some((role) => obj.id == role)) resArr.push(obj);
                        }
                    }
                });
                return resArr;
            };
            let routerMenu = filterAsyncRoutes(list, 0, "");
            //如果是独立的（一级）
            sidebar && routerMenu.forEach(t => {
                if (t.menuType === "C" && (!t.children || t.children.length === 0)) {
                    t.layout = 1;
                    t.children = [{ ...t, layout: 0, alone: 1, children: undefined, }]
                    t.path = "/" + Math.random();
                }
            });
            resolve({ routerMenu, routerArr })
        });

    })
}
//获取路由 侧边栏
router.post("/getRouter", async (req, res) => {
    let { routerMenu, routerArr } = await getRouter(req, res, true);
    function bianpinghua(list) {
        let arr = [];
        list.map(t => {
            if (t.children && t.children.length) arr.push(...bianpinghua(t.children))
            arr.push({ ...t, layout: 1, path: "/" + Math.random(), children: [{ ...t, layout: 0, alone: 1, children: undefined }], hidden: 1 });
        })
        return arr
    }
    routerArr = bianpinghua(routerArr);
    routerArr = routerArr.filter((obj, index, self) => index === self.findIndex((t) => (t.id === obj.id)));
    res.send(utils.returnData0({ data: { routerMenu: routerMenu.concat(routerArr) } }))
});
//菜单管理获取
router.post("/getRouterSystem", async (req, res) => {
    await utils.checkPermi({ req, res, role: [systemSettings.menus.menuQuery] });
    let { routerMenu } = await getRouter(req, res);
    res.send(utils.returnData0({ data: { routerMenu } }));
})
//添加菜单
router.post("/addMenu", async (req, res) => {
    await utils.checkPermi({ req, res, role: [systemSettings.menus.menuAdd] });
    let sql = "INSERT INTO router_menu(parent_id,path,hidden,name,layout,parent_view,meta,component,sort,alone,role_key,menu_type,update_time) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",
        obj = req.body;
    let meta = {};
    await utils.existName({ sql: "SELECT id FROM router_menu WHERE role_key=?", name: obj.roleKey, res, msg: "权限字符已存在！", req });
    await utils.existName({ sql: "SELECT id FROM router_menu WHERE name=?", name: obj.name, res, msg: "页面名称已存在！！", req });
    meta.title = obj.title;
    meta.icon = obj.icon;
    meta.noCache = obj.noCache;
    pool.query(sql, [obj.parentId, obj.path, obj.hidden, obj.name, obj.parentId == 0 ? 1 : 0, obj.parentView, JSON.stringify(meta), obj.component, obj.sort, obj.alone, obj.roleKey, obj.menuType, getCurrentTimeString(),], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});
//修改菜单
router.post("/changeMenu", async (req, res) => {
    await utils.checkPermi({ req, res, role: [systemSettings.menus.menuUp] });
    let sql = "UPDATE  router_menu SET parent_id=?,path=?,hidden=?,name=?,layout=?,parent_view=?,meta=?,component=?,sort=?,alone=?,role_key=?,menu_type=?,update_time=? WHERE id=?",
        obj = req.body;
    let judgeUserNameRes = await utils.judgeUserName({ sql: "SELECT role_key FROM router_menu WHERE  id=?", sqlName: "role_key", name: obj.roleKey, id: obj.id });
    if (judgeUserNameRes === 1) await utils.existName({ sql: "SELECT id FROM router_menu WHERE role_key=?", name: obj.roleKey, res, msg: "权限字符已存在！", req });
    let judgeUserNameRes2 = await utils.judgeUserName({ sql: "SELECT name FROM router_menu WHERE  id=?", sqlName: "name", name: obj.name, id: obj.id });
    let meta = {};
    if (judgeUserNameRes2 === 1) await utils.existName({ sql: "SELECT id FROM router_menu WHERE name=?", name: obj.name, res, msg: "页面名称已存在！", req });
    meta.title = obj.title;
    meta.icon = obj.icon;
    meta.noCache = obj.noCache;
    pool.query(sql, [obj.parentId, obj.path, obj.hidden, obj.name, obj.parentId == 0 ? 1 : 0, obj.parentView, JSON.stringify(meta), obj.component, obj.sort, obj.alone, obj.roleKey, obj.menuType, getCurrentTimeString(), obj.id,], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});
//删除菜单
router.post("/delMenu", async (req, res) => {
    await utils.checkPermi({ req, res, role: [systemSettings.menus.menuDelte] });
    let sql = "DELETE FROM router_menu WHERE id=?";
    let selectSql = "SELECT id FROM router_menu WHERE parent_id=?";
    let obj = req.body;
    pool.query(selectSql, [obj.id], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        if (result.length != 0) return res.send(utils.returnData0({ code: -1, msg: "删除失败，请先删除子级", err, req }));
        pool.query(sql, [obj.id], (err2, result2) => {
            if (err2) return res.send(utils.returnData0({ code: -1, err, req }));
            res.send(utils.returnData0({ data: result }));
        });
    });
});
//查询角色
router.post("/getRoles", async (req, res) => {
    await utils.checkPermi({ req, res, role: [systemSettings.role.roleQuery] });
    let obj = req.body;
    let { page, size } = utils.pageSize(obj.page, obj.size);
    let { total } = await utils.getSum({ name: "roles", where: `WHERE name LIKE "%${obj.name || ''}%"`, res, req });
    let sql = `SELECT id,name,roles,checked_roles AS checkedRoles,role_key AS roleKey,create_time AS createTime FROM roles WHERE name LIKE "%${obj.name || ''}%" LIMIT ?,?`;
    pool.query(sql, [page, size], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result, total }));
    });
});
//查询角色全部
router.post("/getRolesAll", async (req, res) => {
    let sql = `SELECT id,name,roles,checked_roles AS checkedRoles,role_key AS roleKey FROM roles`;
    pool.query(sql, (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});
//添加角色
router.post("/addRoles", async (req, res) => {
    await utils.checkPermi({ req, res, role: [systemSettings.role.roleAdd] });
    let sql = "INSERT INTO roles(name,roles,checked_roles,role_key,create_time) VALUES (?,?,?,?,?)", obj = req.body;
    await utils.existName({ sql: "SELECT id FROM roles WHERE role_key=?", name: obj.roleKey, res, msg: "权限字符已存在！", req });
    // console.log(obj);
    pool.query(sql, [obj.name, obj.roles, obj.checkedRoles, obj.roleKey, getCurrentTimeString()], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});
//修改角色
router.post("/upRoles", async (req, res) => {
    await utils.checkPermi({ req, res, role: [systemSettings.role.roleUp] });
    let sql = "UPDATE  roles SET roles=?,name=?,checked_roles=?,role_key=? WHERE id=?", obj = req.body;
    //总管理不能操作
    await utils.upAdminRole({ req, res, id: obj.id });
    let judgeUserNameRes = await utils.judgeUserName({ sql: "SELECT role_key FROM roles WHERE  id=?", sqlName: "role_key", name: obj.roleKey, id: obj.id });
    if (judgeUserNameRes === 1) await utils.existName({ sql: "SELECT id FROM roles WHERE role_key=?", name: obj.roleKey, res, msg: "权限字符已存在！", req });
    pool.query(sql, [obj.roles, obj.name, obj.checkedRoles, obj.roleKey, obj.id], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});
//删除角色
router.post("/delRoles", async (req, res) => {
    await utils.checkPermi({ req, res, role: [systemSettings.role.roleDelte] });
    let sql = "DELETE FROM roles WHERE id=?", obj = req.body;
    //总管理不能操作
    await utils.upAdminRole({ req, res, id: obj.id });
    pool.query(sql, [obj.id], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});

//添加用户
router.post("/addUser", async (req, res) => {
    await utils.checkPermi({ req, res, role: [systemSettings.user.userAdd] });
    let sql = "INSERT INTO user(name,status,roles_id,remark,pwd,more_id,create_time) VALUES (?,?,?,?,?,?,?)", obj = req.body;
    await utils.existName({ sql: "SELECT id FROM user WHERE  name=?", name: obj.name, res, msg: "用户名已被使用！", req });
    pool.query(sql, [obj.name, obj.status, obj.rolesId, obj.remark, obj.pwd, obj.moreId, getCurrentTimeString()], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err }));
        let themeSql = "INSERT INTO theme(user_id,menu_bg,menu_sub_bg,menu_text,menu_active_text,menu_sub_active_text,menu_hover_bg) VALUES (?,?,?,?,?,?,?)";
        pool.query(themeSql, [result.insertId, "#304156", "#304156", "#bfcad5", "#409eff", "#fff", "#001528"], (themeErr, themeRes) => {
            if (themeErr) return res.send(utils.returnData0({ code: -1, err: themeErr, req }));
            res.send(utils.returnData0({ data: result }));
        })

    });
});

//查询用户
router.post("/getUser", async (req, res) => {
    await utils.checkPermi({ req, res, role: [systemSettings.user.userQuery] });
    let obj = req.body;
    let { page, size } = utils.pageSize(obj.page, obj.size);
    let { total } = await utils.getSum({ name: "user", where: `WHERE username LIKE "%${obj.name || ''}%"`, res, req });
    let sql = `SELECT a.id AS id,openid,username,status,roles_id AS rolesId,admin,a.create_time AS createTime,b.menu_bg AS menuBg,b.menu_sub_bg AS menuSubBg,b.menu_text AS menuText,b.menu_active_text AS menuActiveText,b.menu_sub_active_text AS menuSubActiveText,b.menu_hover_bg AS menuHoverBg FROM user AS a LEFT JOIN theme b ON a.id=b.user_id WHERE username LIKE "%${obj.name || ''}%" LIMIT ?,?`;
    pool.query(sql, [page, size], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result, total }));
    });
});


//修改主题
router.post("/upTheme", async (req, res) => {
    let sql = "UPDATE  theme SET menu_bg=?,menu_sub_bg=?,menu_text=?,menu_active_text=?,menu_sub_active_text=?,menu_hover_bg=? WHERE user_id=?", obj = req.body;
    pool.query(sql, [obj.menuBg, obj.menuSubBg, obj.menuText, obj.menuActiveText, obj.menuSubActiveText, obj.menuHoverBg, obj.id], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});



//修改用户
router.post("/upUser", async (req, res) => {
    await utils.checkPermi({ req, res, role: [systemSettings.user.userUp] });
    let sql = "UPDATE  user SET name=?,status=?,roles_id=?,remark=?,WHERE id=?", obj = req.body;
    //总管理不能操作
    await utils.upAdmin({ req, res, id: obj.id });
    let judgeUserNameRes = await utils.judgeUserName({ sql: "SELECT name FROM user WHERE  id=?", name: obj.name, id: obj.id });
    if (judgeUserNameRes === 1) await utils.existName({ sql: "SELECT id FROM user WHERE  name=?", name: obj.name, res, msg: "用户名已被使用！", req });
    pool.query(sql, [obj.name, obj.status, obj.rolesId, obj.remark, obj.id], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});

//修改用户密码
router.post("/upUserPwd", async (req, res) => {
    await utils.checkPermi({ req, res, role: [systemSettings.user.userPwd] });
    let sql = "UPDATE  user SET pwd=? WHERE id=?", obj = req.body;
    let getUserIdRes = await utils.getUserId({ id: obj.id, req, res });
    if (getUserIdRes.admin === 1) {
        let user = await utils.getUserInfo(req, res);
        if (user.admin !== 1) return res.send(utils.returnData0({ code: -1, msg: "总管理密码只能总管理账号修改！", req }));
    }
    pool.query(sql, [obj.pwd, obj.id], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});

//删除用户
router.post("/delUser", async (req, res) => {
    await utils.checkPermi({ req, res, role: [systemSettings.user.userDelte] });
    let obj = req.body;
    //总管理不能操作
    await utils.upAdmin({ req, res, id: obj.id });
    let user = await utils.getUserInfo(req, res);
    if (obj.id == user.id) return res.send(utils.returnData0({ code: -1, msg: "无法删除正在使用中的用户~", req }));
    let sql = "DELETE FROM user WHERE id=?";
    pool.query(sql, [obj.id], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err: err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});


//添加多账号
router.post("/addMore", async (req, res) => {
    await utils.checkPermi({ req, res, role: [systemSettings.more.moreAdd] });
    let sql = "INSERT INTO more(name,remark,create_time) VALUES (?,?,?)", obj = req.body;
    await utils.existName({ sql: "SELECT id FROM more WHERE  name=?", name: obj.name, res, msg: "账号名已存在！", req });
    pool.query(sql, [obj.name, obj.remark, getCurrentTimeString()], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});
//查询多账号
router.post("/getMore", async (req, res) => {
    await utils.checkPermi({ req, res, role: [systemSettings.more.moreQuery] });
    let obj = req.body;
    let { page, size } = utils.pageSize(obj.page, obj.size);
    let { total } = await utils.getSum({ name: "more", where: `WHERE name LIKE "%${obj.name || ''}%"`, res, req });
    let sql = `SELECT id,name,remark,create_time AS createTime FROM more WHERE name LIKE "%${obj.name || ''}%" LIMIT ?,?`;
    pool.query(sql, [page, size], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result, total }));
    });
});
//查询多账号 全部
router.post("/getMoreAll", async (req, res) => {
    let sql = "SELECT id,username,display as remark FROM user";
    pool.query(sql, (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});
//修改多账号
router.post("/upMore", async (req, res) => {
    await utils.checkPermi({ req, res, role: [systemSettings.more.moreUp] });
    let sql = "UPDATE  more SET name=?,remark=? WHERE id=?", obj = req.body;
    pool.query(sql, [obj.name, obj.remark, obj.id], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});
//删除多账号
router.post("/delMore", async (req, res) => {
    await utils.checkPermi({ req, res, role: [systemSettings.more.moreDelte] });
    let sql = "DELETE FROM more WHERE id=?", obj = req.body;
    pool.query(sql, [obj.id], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});

//添加字典
router.post("/addDict", async (req, res) => {
    let sql = "INSERT INTO dict(name,type,create_time,remark) VALUES (?,?,?,?)", obj = req.body;
    await utils.existName({ sql: "SELECT id FROM dict WHERE  type=?", name: obj.type, res, msg: "字典类型已存在！", req });
    pool.query(sql, [obj.name, obj.type, getCurrentTimeString(), obj.remark], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});
//查询字典
router.post("/getDict", async (req, res) => {
    let obj = req.body;
    let sql = `SELECT id,name,create_time AS createTime,remark,type FROM dict WHERE name LIKE "%${obj.name || ''}%" LIMIT ?,?`;
    let { total } = await utils.getSum({ name: "dict", where: `WHERE name LIKE "%${obj.name || ''}%"`, res, req });
    let { page, size } = utils.pageSize(obj.page, obj.size);
    pool.query(sql, [page, size], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result, total }));
    });
});

//查询字典(不分页)
router.post("/getDictAll", async (req, res) => {
    let obj = req.body;
    let sql = `SELECT id,name,create_time AS createTime,remark,type FROM dict WHERE name LIKE "%${obj.name || ''}%"`;
    pool.query(sql, (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});

//修改字典
router.post("/upDict", async (req, res) => {
    let sql = "UPDATE  dict SET name=?,type=?,remark=? WHERE id=?", obj = req.body;
    let judgeUserNameRes = await utils.judgeUserName({ sql: "SELECT type FROM dict WHERE  id=?", name: obj.type, id: obj.id, sqlName: "type" });
    if (judgeUserNameRes === 1) await utils.existName({ sql: "SELECT id FROM dict WHERE  type=?", name: obj.type, res, msg: "字典类型已存在！", req });

    pool.query(sql, [obj.name, obj.type, obj.remark, obj.id], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});

//删除字典
router.post("/delDict", async (req, res) => {
    let sql = "DELETE FROM dict WHERE id=?", obj = req.body;
    pool.query(sql, [obj.id], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});

//添加字典项目
router.post("/addDictItem", async (req, res) => {
    let sql = "INSERT INTO dict_item(dict_id,dict_label,dict_value,dict_sort,dict_class,status,create_time,remark) VALUES (?,?,?,?,?,?,?,?)", obj = req.body;
    pool.query(sql, [obj.dictId, obj.dictLabel, obj.dictValue, obj.dictSort, obj.dictClass, obj.status, getCurrentTimeString(), obj.remark], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});

//查询字典项目
router.post("/getDictItem", async (req, res) => {
    let obj = req.body;
    let sql = `SELECT a.id AS id,dict_id AS dictId,dict_label AS dictLabel,dict_value AS dictValue,dict_sort AS dictSort,dict_class AS dictClass,status,a.create_time AS dictItemCreateTime,a.remark AS remark,type FROM dict_item AS a LEFT JOIN dict b ON a.dict_id=b.id WHERE dict_id=? ORDER BY dict_sort ASC`;
    pool.query(sql, [obj.dictId], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});

//修改字典项目
router.post("/upDictItem", async (req, res) => {
    let obj = req.body;
    let sql = `UPDATE  dict_item SET dict_label=?,dict_value=?,dict_sort=?,dict_class=?,status=?,remark=? WHERE id=?`;
    pool.query(sql, [obj.dictLabel, obj.dictValue, obj.dictSort, obj.dictClass, obj.status, obj.remark, obj.id], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});
//删除字典项目
router.post("/delDictItem", async (req, res) => {
    let sql = "DELETE FROM dict_item WHERE id=?", obj = req.body;
    pool.query(sql, [obj.id], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});

//根据类型查询字典项目
router.post("/getDictType", async (req, res) => {
    let obj = req.body;
    let sql = `SELECT a.id AS id,dict_label AS dictLabel,dict_value AS dictValue,dict_sort AS dictSort,dict_class AS dictClass,a.remark AS remark,type FROM dict_item AS a LEFT JOIN dict b ON a.dict_id=b.id WHERE b.type=? AND a.status=1 ORDER BY dict_sort ASC`;
    pool.query(sql, [obj.type], (err, result) => {
        if (err) return res.send(utils.returnData0({ code: -1, err, req }));
        res.send(utils.returnData0({ data: result }));
    });
});



module.exports = router;
